package com.cw.paging3

import androidx.paging.PagingSource
import androidx.paging.PagingState

class PostDataSource(private val apiService: APIService) : PagingSource<Int, Data>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Data> {
        try {
            // param.key为空时，默认加载第1页数据
            val currentLoadingPageKey = params.key ?: 1
            val response = apiService.getListData(currentLoadingPageKey)
            val responseData = mutableListOf<Data>()
            val data = response.data
//            responseData.addAll(data)
            // 请求成功使用LoadResult.Page返回分页数据，prevKey 和 nextKey 分别代表前一页和后一页的索引。
            val prevKey = if (currentLoadingPageKey == 1) null else currentLoadingPageKey - 1
            val nextKey = if (currentLoadingPageKey < response.totalPages) currentLoadingPageKey + 1 else null
//            return LoadResult.Page(
//                data = responseData,
//                prevKey = prevKey,
//                nextKey = currentLoadingPageKey.plus(1)
//            )
            return LoadResult.Page(data, null, nextKey)
        } catch (e: Exception) {
            e.printStackTrace()
            // 请求失败使用LoadResult.Error返回错误状态
            return LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Data>): Int? = null

}